package com.tarena.luban.demo.all.adapter.service.impl;


import com.tarena.luban.demo.all.adapter.mapper.OrderMapper;
import com.tarena.luban.demo.all.service.ICartService;
import com.tarena.luban.demo.all.service.IOrderService;
import com.tarena.luban.demo.all.service.IStockService;
import com.tarena.luban.commons.pojo.order.dto.OrderAddDTO;
import com.tarena.luban.commons.pojo.order.entity.Order;
import com.tarena.luban.commons.pojo.stock.dto.StockReduceCountDTO;
import com.tarena.luban.commons.restful.JsonPage;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

// order模块是具备生产者特征的,它会被business模块调用,所以也要加@DubboService注解
@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    //使得当前接口的实现,在order 会套用dubbo远程调用
    @DubboReference(loadbalance = "roundrobin")
    private IStockService stockService;
    @DubboReference(loadbalance = "roundrobin")
    private ICartService cartService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void orderAdd(OrderAddDTO orderAddDTO) {
        // 先来查询当前订单是否存在了,如果订单存在当前方法结束
        // 不存在 向下之后后续逻辑
        //select count(id) from order_tbl where commodity_code=#{} and user_id=#{}
        int result=orderMapper.selectCountByCommodityCodeAndUserId(orderAddDTO);
        if (result>0){
            log.info("订单已经存在,方法重复调用");
            return;
        }
        doReduceCount(orderAddDTO);
        Order order=new Order();
        BeanUtils.copyProperties(orderAddDTO,order);
        orderMapper.insertOrder(order);
        log.info("新增订单信息为:{}",order);
        cartService.deleteUserCart(orderAddDTO.getUserId(), orderAddDTO.getCommodityCode());
    }

    private void doReduceCount(OrderAddDTO orderAddDTO) {
        StockReduceCountDTO countDTO=new StockReduceCountDTO();
        countDTO.setCommodityCode(orderAddDTO.getCommodityCode());
        countDTO.setReduceCount(orderAddDTO.getCount());
        stockService.reduceCommodityCount(countDTO);
    }

    public JsonPage<Order> getAllOrdersByPage(Integer page, Integer pageSize){
        PageHelper.startPage(page,pageSize);
        List<Order> list = orderMapper.findAllOrders();
        return JsonPage.restPage(new PageInfo<>(list));
    }
}







